/*
** test.c for  in /home/gomes_m//workzone/ftp
** 
** Made by mickael gomes
** Login   <gomes_m@epitech.net>
** 
** Started on  Tue Apr  9 20:14:33 2013 mickael gomes
** Last update Thu Apr 11 14:52:15 2013 mickael gomes
*/

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>

void		gere_cmd(int client_fd, char *cmd)
{
  int			pipefd[2];
  int			pid;
  int			status;
  int			len;
  char			*cul[2];
  char			buff[512];

  cul[0] = cmd;
  cul[1] = NULL;
  if (strcmp(cmd, "ls\n") && strcmp(cmd, "pwd\n"))
    return ;
  printf("Cul.\n");
  pipe(pipefd);
  pid = fork();
  wait(&status);
  if (pid == 0)
    {
      close(pipefd[0]);
      dup2(pipefd[1], 1);
      if (!strcmp(cmd, "ls\n"))
	execve("/bin/ls", cul, NULL);
      else
	execve("/bin/pwd", cul, NULL);
    }
  else
    {
      close(pipefd[1]);
      len = read(pipefd[0], buff, 511);
      buff[len] = 0;
      write(client_fd, buff, len);
    }
}

void		gere_client(int client_fd, char *buff)
{
  int			pid;
  int			status;

  pid = fork();
  wait(&status);
  if (pid == 0)
    gere_cmd(client_fd, buff);
  else
    exit(EXIT_SUCCESS);
}

int		main(int ac, char **av)
{
  int			pid;
  int			status;
  int			fd;
  int			port;
  int			client_fd;
  char			*client_ip;
  socklen_t		s_in_size;
  struct protoent	*pe;
  struct sockaddr_in	s_in;
  struct sockaddr_in	s_in_client;
  char                  *poil[3];
  int			len;
  char			buff[512];

  poil[0] = "grep";
  poil[1] = "vache";
  poil[2] = NULL;
  if (ac != 2)
    return (1);
  s_in_size = sizeof(s_in_client);
  port = atoi(av[1]);
  pe = getprotobyname("TCP");
  fd = socket(AF_INET, SOCK_STREAM, pe->p_proto);
  if (fd == -1)
    return (1);
  s_in.sin_family = AF_INET;
  s_in.sin_port = htons(port);
  s_in.sin_addr.s_addr = INADDR_ANY;
  bind(fd, (const struct sockaddr *)&s_in, sizeof(s_in));
  listen(fd, 42);
  while ((client_fd = accept(fd, (struct sockaddr *)&s_in_client, &s_in_size)) != -1)
    {
      pid = fork();
      if (pid == 0)
	{
	  while ((len = read(client_fd, buff, 512)) > 0)
	    {
	      buff[len] = 0;
	      gere_cmd(client_fd, buff);
	    }
	}
      else
	close(client_fd);  
    }
  return (0);
}
